<template>
    <!-- 事实外包方-新增 -->
    <div class="e-form">
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    label-width="150px"
                    :rules="rules"
                    ref="formData"
                >
 <BillTop title="事实外包方新增" @cancel="handleClose"></BillTop>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="统一社会信用代码"
                                prop="creditCode"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.creditCode"
                                    maxlength="18"
                                    @change="initialization1"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="外包方类别" prop="type">
                                <el-radio-group
                                    :disabled="isBringIn"
                                    v-model="formData.type"
                                    @change="initialization3"
                                >
                                    <el-radio  :label="0">分包商</el-radio>

                                    <el-radio  :label="1">供应商</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="外包方名称：" prop="outerName">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.outerName"
                                     :disabled="isBringIn"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="法人代表" prop="deputy">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.deputy"
                                    :disabled="isBringIn"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="法人身份证号码："
                                prop="idCard"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.idCard"
                                    :disabled="isBringIn"
                                    maxlength="18"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="法人身份证附件:"
                                prop="deputyOssName"
                            >
                                <span
                                    @click="preview1()"
                                    style="
                                        disply: inline-block;
                                        width: 100%;
                                        color: blue;
                                        cursor: pointer;
                                        overflow: hidden;
                                    "
                                    >{{ formData.deputyOssName }}</span
                                >
                                <el-upload
                                    style="margin: 7px 5px 0px 0px"
                                    class="upload-demo"
                                    :action="uploadUrl"
                                    :data="{
                                        bucketName,
                                        relationId,
                                        orgCode
                                    }"
                                    :before-upload="beforeAvatarUpload"
                                    :accept="accept"
                                    :on-success="attachOnSuccess"
                                    :http-request="uploadBefore"
                                    :show-file-list="false"
                                    name="files"
                                >
                                    <el-button
                                        v-show="!isBringIn"
                                        type="primary"
                                        >上传</el-button
                                    >
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="注册资本(万元)："
                                prop="registeredCapital"
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.registeredCapital"
                                    v-enterFloat2
                                    :disabled="isBringIn"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="营业执照"
                                prop="businessLicenseOssName"
                            >
                                <span
                                    @click="preview2()"
                                    style="
                                        disply: inline-block;
                                        width: 100%;
                                        color: blue;
                                        cursor: pointer;
                                        overflow: hidden;
                                    "
                                    >{{ formData.businessLicenseOssName }}</span
                                >
                                <el-upload
                                    style="margin: 7px 5px 0px 0px"
                                    class="upload-demo"
                                    :action="uploadUrl"
                                    :data="{
                                        bucketName,
                                        relationId,
                                        orgCode
                                    }"
                                    :before-upload="beforeAvatarUpload"
                                    :accept="accept"
                                    :on-success="attachOnSuccessBl"
                                    :http-request="uploadBeforeBl"
                                    :show-file-list="false"
                                    name="files"
                                >
                                    <el-button
                                        v-show="!isBringIn"
                                        type="primary"
                                        >上传</el-button
                                    >
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="库外单位">
                                <el-switch
                                    :width="60"
                                    v-model="formData.isOutOrg"
                                    class="main-el-switch"
                                    active-color="#13ce66"
                                    inactive-color="#D2D2D2"
                                    active-value="1"
                                    inactive-value="0"
                                    active-text="是"
                                    inactive-text="否"
                                    disabled
                                >
                                </el-switch>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="录入机构">{{
                                formData.orgName
                            }}</el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="注册地址" prop="address">
                                <SelectAddr
                                    v-model="formData.address"
                                    lazy
                                    showCountry
                                    style="width: 100%"
                                    :disabled="isBringIn"
                                ></SelectAddr>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态:">
                                {{ statusLable(formData.state) }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="备注:">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    v-model="formData.remarks"
                                    placeholder="请输入内容"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                >保存</el-button
            >
            <el-button @click="cancel()">取消</el-button>
        </div>
    </div>
</template>

<script>
import SelectAddr from '@/components/common/addrComp'
// 事实外包方
import correspondentUnit from '@/api/OutsourcingartyAdmin/correspondentUnit/correspondentUnit.js'
import Withtheunit from '@/api/OutsourcingartyAdmin/Withtheunit/Withtheunit.js'
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import ossRequest from '@/api/oss/oss.js'
// import { showSuccessPop } from '@/utils/common'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import { creditCodeVerification, isIdcard } from '@/utils/rules'
export default {
    data () {
        return {
            //表单数据
            bucketName: 'factualOutsourcerAdmin',
            formData: {
                address: '', //	注册地址
                businessLicenseOss: '', //	营业执照附件主键
                businessLicenseOssName: '', //营业执照
                creditCode: '', //统一信用代码
                deputy: '', //法人
                deputyOss: '', //法人附加主键
                deputyOssName: '', //法人身份附件名字
                id: '', //主键
                idCard: '', //法人身份证
                isOutOrg: '', //是否是库外单位（0 不是 1是)
                orgId: '', //机构id
                orgName: '', //机构名称
                outerName: '', //外包方名称
                registeredCapital: null, //注册资本
                state: 0, //	单据状态
                type: '', //外包方类型（0 分包商 1 供应商）
                dialogImageUrl: '', //法人附加主键路径
                businessLicenseOssImage: '', //营业执照附件路径
                remarks: '', //备注
            },
            businessList: [],
            // 初始化参数
            initializationData: {
                creditCode: '', //信用代码
                deputy: '', //	法人
                idCard: '', //	法人身份证
                outerName: '', //外包方名称
                type: null //外包方类型（0 分包商 1 供应商）
            },
            unitList: [],
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            isBringIn: false, //是否带入数据
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,.jpeg,.png,.pdf',
            relationId: '',
            isNull: false, //是否有数据填入
            newData: {}, //库内查出来的数据进行保存
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: creditCodeVerification,
                        trigger: 'blur'
                    }
                ],
                //外包方类型
                type: [
                    {
                        required: true,
                        message: '请选择外包方类型',
                        trigger: 'blur'
                    }
                ],
                //外包方名称
                outerName: [
                    {
                        required: true,
                        message: '请输入外包方名称',
                        trigger: 'blur'
                    }
                ],
                //法人代表
                deputy: [
                    {
                        required: true,
                        message: '请输入法人代表',
                        trigger: 'blur'
                    }
                ],
                //法人身份证号码
                idCard: [
                    {
                        required: true,
                        validator: isIdcard,
                        trigger: 'blur'
                    }
                ],
                //法人身份证附件
                deputyOssName: [
                    {
                        required: true,
                        message: '请上传法人身份证附件',
                        trigger: 'change'
                    }
                ],
                //注册资本
                registeredCapital: [
                    {
                        required: true,
                        message: '请输入注册资本',
                        trigger: 'blur'
                    }
                ],
                //营业执照
                businessLicenseOssName: [
                    {
                        required: true,
                        message: '请上传营业执照',
                        trigger: 'change'
                    }
                ],
                //注册地址
                address: [
                    {
                        required: true,
                        message: '请选择注册地址',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    components: {
        SelectAddr
    },
    created () {
        this.getBusinesseData()
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.formData.orgId = data.userInfo.orgInfo.orgId
        this.formData.orgName = data.userInfo.orgInfo.orgName
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    beforeDestroy () {},
    methods: {
        ...mapMutations(['setPopConfirm']),
        //获取业务类型数据
        getBusinesseData () {
            call.getCredential('往来单位业务类型').then(res => {
                this.businessList = res
            })
            call.getCredential('往来单位类型').then(res => {
                this.unitList = res
            })
        },
        //保存按钮
        save () {
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    let data = JSON.parse(JSON.stringify(this.formData))
                    let datas = await correspondentUnit.correspondentUnitAdd(
                        data
                    )
                    if (datas.code != 200) {
                        this.clientPop(
                            'info',
                            '保存成功！是否进行下一步操作？',
                            this.gocallback(datas),
                            null,
                            this.cancelCallBack(datas)
                        )
                    }
                }
            })
        },
        // 保存成功继续回调
        gocallback (billid) {
            return () => {
                this.$router.push({
                    path: '/FactualOutsourcerEdit',
                    query: { billid }
                })
            }
        },
        // 保存成功，取消回调
        cancelCallBack (billid) {
            return () => {
                this.$router.push({
                    path: '/FactualOutsourcer',
                    query: { billid }
                })
            }
        },
        //取消按钮
        cancel () {
            this.$router.push('/FactualOutsourcer')
        },
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    this.formData.deputyOssName = res[0].objectName
                    this.formData.deputyOss = res[0].relationId
                    this.formData.deputyOssImage = res[0].objectPath
                })
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccess()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //营业执照上传成功
        attachOnSuccessBl () {
            this.getObjectByRelationIdBl()
        },
        //获取上传成功的对象
        getObjectByRelationIdBl () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    // 等后端确定id和名字。再赋值
                    this.formData.businessLicenseOssName = res[0].objectName
                    this.formData.businessLicenseOss = res[0].relationId
                    this.formData.businessLicenseOssImage = res[0].objectPath
                })
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBeforeBl (params) {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    params.data.relationId = res[0]
                    this.relationId = res[0]
                    let obj = {
                        ...params.data,
                        files: params.file
                    }
                    this.$Ajax
                        .httpPostForm({
                            url: this.uploadUrl,
                            params: obj
                        })
                        .then(() => {
                            this.attachOnSuccessBl()
                        })
                })
                .catch(error => {
                    this.clientPop('err', error, this.handleClose)
                })
        },
        //预览法人附件
        preview1 () {
            if (this.formData.deputyOssImage) {
                window.open(this.formData.deputyOssImage)
            }
        },
        //营业执照预览附件
        preview2 () {
            if (this.formData.businessLicenseOssImage) {
                window.open(this.formData.businessLicenseOssImage)
            }
        },
        // 判断是否填写了数据
        isData () {
            // 外包方名称
            if(this.formData.outerName != '' && this.formData.outerName != null) {
                this.isNull = true
            }
            // 法人代表
            if(this.formData.deputy != '' && this.formData.deputy != null) {
                this.isNull = true
            }
            // 法人身份证号码
            if(this.formData.idCard != '' && this.formData.idCard != null) {
                this.isNull = true
            }
            //法人身份证附件
            if(this.formData.deputyOssName != '' && this.formData.deputyOssName != null) {
                this.isNull = true
            }
            // 注册资本
            if(this.formData.registeredCapital != '' && this.formData.registeredCapital != null) {
                this.isNull = true
            }
            // 营业执照
            if(this.formData.businessLicenseOssName != '' && this.formData.businessLicenseOssName != null) {
                this.isNull = true
            }
            // 备注
            if(this.formData.remarks != '' && this.formData.remarks != null) {
                this.isNull = true
            }

        },
        // 信用代码
        initialization1 (val) {
            this.initializationData.creditCode = val
            this.initialization()

        },
        //类型
        initialization3 (val) {
            this.initializationData.type =  val
            this.initialization()
        },
        // 初始化
        async initialization () {
            let data = await Withtheunit.WiththeunitInitialization(
                this.initializationData
            )
            // 将查回来的数据进行保存
            if (data.code != 200) {
                this.newData = data
                // 如果有数据，则判断基础信息是否填写
                this.isData()
                if(this.isNull) {
                    // 如果填写，则提示是否覆盖
                    this.clientPop('info', '修改后的统一社会信用代码，在外包方库存在，是否清空已有数据并带入外包方库中的数据？', this.callback1, null, this.cancelCallBack1)
                }else{
                    // 未填写，则直接赋值
                    this.callback1()
                    this.isNull = false
                }

            } else {
                this.isData()
                if(this.isNull) {
                    this.clientPop('info', '修改后的统一社会信用代码，是否清空已有数据？', this.callback2, null, this.cancelCallBack1)
                }

            }
        },
        // 取消方法
        cancelCallBack1 () {
            this.$set(this.formData, 'creditCode', this.newData.creditCode)
        },
        // 库内存在，确认带入数据之后，再带入数据
        callback1 () {
            this.formData.creditCode = this.newData.creditCode
            this.formData.type =  this.newData.type//外包方类型
            this.formData.outerName =  this.newData.outerName //外包方名称
            this.formData.deputy =  this.newData.deputy//法人代表
            this.formData.deputyOss =  this.newData.deputyOss //法人id
            this.formData.idCard =  this.newData.idCard //法人身份证
            this.formData.dialogImageUrl =  this.newData.dialogImageUrl //法人附件路径
            this.formData.businessLicenseOssImage =  this.newData.businessLicenseOssImage //营业执照路径
            this.formData.businessLicenseOss =  this.newData.businessLicenseOss //
            this.formData.businessLicenseOssName =  this.newData.businessLicenseOssName //
            this.formData.deputyOssName =  this.newData.deputyOssName //
            this.formData.isOutOrg = '0' //库内单位
            this.formData.outerName =  this.newData.outerName //
            this.formData.registeredCapital =  this.newData.registeredCapital //
            this.formData.address =  this.newData.address //注册地址
            this.formData.creditCode =  this.newData.creditCode //信用代码
            // 是否带入数据
            this.isBringIn = true
        },
        // 库内不存在
        callback2 () {
            // 是否带入数据
            this.isBringIn = false
            this.formData = this.$options.data().formData
            //情空之后，将是否有数据的字段改为false
            this.isNull = false
            // 如果未查出数据，则证明是库外单位
            this.formData.isOutOrg = '1'
            // 如果是默认值，则将用户输入的值保留，默认值也保留
            this.formData.creditCode = this.initializationData.creditCode
            this.formData.type = this.initializationData.type
            this.formData.orgId = JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId
            this.formData.orgName = JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
// 境外单位
::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
